import * as React from 'react'
import classNames from 'classnames'
import { Icon } from '../../components'
import { CardGroupContext } from './card-group'
import { CardItemProps, CardItemState, CardGroupContextInteface } from './interface'

const defaultProps = {
  prefixCls: 'layui-colla'
}

const checkIsUndefined = (val: any) => {
  return val === undefined
}

// 改造为函数式组件 使用useContext
const CardItem = React.forwardRef(
  (props: CardItemProps, ref) => {
    const {
      className, children, title,
      onClick, eventKey,
      ...restProps
    } = props
    const { prefixCls } = defaultProps
    const { activeKey, updateActiveKey, defaultActiveKey } = React.useContext<CardGroupContextInteface>(CardGroupContext)
    // console.log(eventKey + ' => ' + activeKey);
    // 判断是否显示
    // const [data, setData] = React.useState({ isShow: activeKey ? (eventKey == activeKey) : false })
    // 上面写法默认状态不更新
    const [data, setData] = React.useState({ isShow: eventKey == defaultActiveKey })
    const { isShow } = data
    if (!checkIsUndefined(activeKey) && (eventKey == activeKey) != isShow) {
      setData({
        isShow: eventKey == activeKey
      })
    }
    const classes = classNames(`${prefixCls}-item`, className, {

    })
    const contentClasses = classNames(`${prefixCls}-content`, {
      ['layui-show']: isShow
    })


    const handleClick = () => {
      // 判断是不是手风琴状态
      if (!checkIsUndefined(defaultActiveKey)) {
        console.log('change');
        // 如果当前已经是打开状态则赋值为空
        updateActiveKey?.(isShow ? '' : eventKey)
      } else {
        setData({
          isShow: !isShow
        })
      }
    }

    return (
      <div
        className={classes}
        {...restProps}
        onClick={handleClick}
      >
        {title ? <h2 className={`${prefixCls}-title`}>
          {title}
          {/* 图标 */}
          <Icon className={`${prefixCls}-icon`} type={isShow ? 'down' : 'right'} />
        </h2> : ''}
        <div className={contentClasses}>
          {children}
        </div>
      </div>
    )
  }
)
export default CardItem